﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.Extensions;
using MShop.Core.DataAccess;
using MShop.Core.Domain;
using MShop.Core;
using MShop.Web.Models;
using System.Collections.Specialized;
using MShop.Core.Epay.Ali;

namespace MShop.Web.Controllers
{
    public class TradeController : ControllerBase
    {
        private readonly IProductDao _ProductDao;
        private readonly IItemCatDao _ItemCatDao;
        private readonly ICartItemDao _CommonDao;
        private readonly IPayDao _PayDao;
        private readonly ICommonDao<Distribution> _CommonDao2;
        private readonly IShopContext _ShopContext;
        private readonly IAreaGroupDao _AreaGroupDao;
        private readonly ICommonDao<ShopUsersAddress> _CommonDao3;
        private readonly ITradeDao _TradeDao;
        private readonly IPayPluginDao _PayPluginDao;
        public TradeController(IProductDao productDao, IItemCatDao itemcatdao, IBrandDao brandDao, ISupplierDao supplierDao,
            ICartItemDao commonDao, IShopContext shopContext, IPayDao payDao, ICommonDao<Distribution> commonDao2, IAreaGroupDao areaGroupDao,
            ICommonDao<ShopUsersAddress> commonDao3, ITradeDao tradeDao, IPayPluginDao payPluginDao
            )
        {
            _ItemCatDao = itemcatdao;
            _ProductDao = productDao;
            _CommonDao = commonDao;
            _ShopContext = shopContext;
            _PayDao = payDao;
            _CommonDao2 = commonDao2;
            _AreaGroupDao = areaGroupDao;
            _CommonDao3 = commonDao3;
            _TradeDao = tradeDao;
            _PayPluginDao = payPluginDao;
        }
        public ActionResult Index()
        {
            return View(_ProductDao.GetAll());
        }

        public ActionResult Delete(int id)
        {
            CartItem cartitem = _CommonDao.GetById(id);
            _CommonDao.Delete(cartitem);
            _CommonDao.SaveChanges();
            return RedirectToAction("mycart");
        }

        public ActionResult MyCart()
        {
            AppendMeta("我的购物车");
            if (User.Identity.IsAuthenticated)
            {
                return View(_CommonDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId));
            }
            else
            {
                return View(_CommonDao.Find(x => x.SessionId == _ShopContext.SessionId));
            }
        }

        [HttpPost]
        public ActionResult MyCart(FormCollection form)
        {
            AppendMeta("我的购物车");
            if (User.Identity.IsAuthenticated)
            {
                _CommonDao.DeleteCartItems(_ShopContext.CurrentUser.UserId);
                _CommonDao.SaveChanges();
            }
            else
            {
                _CommonDao.DeleteCartItems(_ShopContext.SessionId);
                _CommonDao.SaveChanges();
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ShoppingCartSelect(string token, string tradeid)
        {
            AppendMeta("确认订单信息");
            Trade trade = new Trade();
            if (User.Identity.IsAuthenticated == false)
            {
                string returnUrl = "/trade/ShoppingCartSelect";
                return RedirectToAction("Logon", "Account", new { @ReturnUrl = returnUrl });
            }

            ShopUsersAddress[] address = _CommonDao3.Find(x => x.UserId == _ShopContext.CurrentUser.UserId).ToArray();
            ViewData["address"] = address;
            AreaGroup areagourp = null;
            ShopUsersAddress defaultaddress = null;
            string currencyid = _ShopContext.Settings.CurrencyId.ToString();


            var pays = _PayDao.Find(x => x.CurrenyUnits.Contains(currencyid)).OrderBy(x => x.Sort);
            pays.ToList().ForEach(x =>
            {
                x = _PayDao.GetById(x.Id);
            });
            ViewData.Add("Pays", pays);

            ViewData.Add("Distributions", _CommonDao2.GetAll());
            ViewData["distprice"] = _CommonDao2.GetAll().First().Price;

            if (string.IsNullOrEmpty(token) && string.IsNullOrEmpty(tradeid))
            {

                _TradeDao.DeleteInvalidTrade(_ShopContext.CurrentUser.UserId, new TimeSpan(0, 3, 0));
                _TradeDao.SaveChanges();
                if (address.Count() > 0)
                {
                    if (address.Any(x => x.IsDefault))
                    {
                        defaultaddress = address.First(x => x.IsDefault);
                        areagourp = address.First(x => x.IsDefault).AreaGroup;

                    }
                    else
                    {
                        defaultaddress = address.First();
                        areagourp = address.First().AreaGroup;
                    }
                }
                if (areagourp != null)
                {
                    ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null), areagourp.Id, areagourp);
                }
                else
                {
                    ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null));
                }

                decimal totalFee = 0;
                ViewData.Add("CartItems", _CommonDao.GetCurrentCartItems(User.Identity.IsAuthenticated, _ShopContext, out totalFee));

                if (defaultaddress != null)
                {

                    trade.Location = defaultaddress.Location;
                    trade.Mobile = defaultaddress.Mobile;
                    trade.PostCode = defaultaddress.Postcode;
                    trade.ReceiverName = defaultaddress.ReceiverName;
                    trade.Tel = defaultaddress.Tel;

                }
                ViewData["totalfee"] = totalFee;

                return View(trade);
            }
            else
            {
                trade = _TradeDao.Find(x => x.TradeId == tradeid && x.Token == token).FirstOrDefault();

                ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null), trade.AreaGroup.Id, trade.AreaGroup);

                decimal totalFee = 0;
                ViewData.Add("CartItems", _CommonDao.GetCurrentCartItems(User.Identity.IsAuthenticated, _ShopContext, out totalFee));
                ViewData["totalfee"] = totalFee;
                if (trade != null)
                {
                    ViewData["distprice"] = _CommonDao2.FirstOrDefault(x => x.Id == trade.DistributionId).Price;
                    return View(trade);
                }
                throw new ArgumentNullException();
            }
        }


        [HttpPost]
        [Authorize]
        public ActionResult ShoppingCartSelect(string token, string tradeid, [Bind(Exclude = "TradeId")] Trade mytrade)
        {



            AppendMeta("确认订单信息");
            ShopUsersAddress[] address = _CommonDao3.Find(x => x.UserId == _ShopContext.CurrentUser.UserId).ToArray();
            ViewData["address"] = address;
            AreaGroup areagourp = null;
            ShopUsersAddress defaultaddress = null;
            ViewData["distprice"] = _CommonDao2.GetAll().First().Price;
            string currencyid = _ShopContext.Settings.CurrencyId.ToString();


            if (address.Count() > 0)
            {
                if (address.Any(x => x.IsDefault))
                {
                    defaultaddress = address.First(x => x.IsDefault);
                    areagourp = address.First(x => x.IsDefault).AreaGroup;

                }
                else
                {
                    defaultaddress = address.First();
                    areagourp = address.First().AreaGroup;
                }
            }
            if (areagourp != null)
            {
                ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null), areagourp.Id, areagourp);
            }
            else
            {
                ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null));
            }

            var pays = _PayDao.Find(x => x.CurrenyUnits.Contains(currencyid)).OrderBy(x => x.Sort);
            pays.ToList().ForEach(x =>
            {
                x = _PayDao.GetById(x.Id);
            });
            ViewData.Add("Pays", pays);

            ViewData.Add("Distributions", _CommonDao2.GetAll());

            decimal totalFee = 0;
            ViewData.Add("CartItems", _CommonDao.GetCurrentCartItems(User.Identity.IsAuthenticated, _ShopContext, out totalFee));

            if (string.IsNullOrEmpty(token) && string.IsNullOrEmpty(tradeid))
            {
                mytrade.UserId = _ShopContext.CurrentUser.UserId;
                mytrade.TradeStatus = 1;
                mytrade.Token = Session.SessionID;
                foreach (var item in _CommonDao.GetCurrentCartItems(User.Identity.IsAuthenticated, _ShopContext, out totalFee))
                {
                    Order order = new Order();
                    order.ProductId = item.ProductId;
                    order.OrderPrice = item.Price;
                    order.OrderNum = item.Quanitiy;
                    order.OrderPoint = item.Point;
                    order.ProductName = item.ProductName;
                    mytrade.Order.Add(order);
                }
                ViewData["totalfee"] = totalFee;
                mytrade.TotalFee = totalFee;
                mytrade.TotalPoint = mytrade.Order.Sum(x => x.OrderPoint);
                if (ModelState.IsValid)
                {
                    mytrade.PostFee = _CommonDao2.GetById(mytrade.DistributionId).Price;
                    _TradeDao.Save(mytrade);
                    _TradeDao.SaveChanges();
                    return RedirectToAction("ConfirmTrade", "Trade", new { token = mytrade.Token, tradeid = mytrade.TradeId });
                }
                else
                {
                    return View(mytrade);
                }
            }
            else
            {
                Trade dbtrade = _TradeDao.FirstOrDefault(x => x.TradeId == tradeid && x.Token == token);
                UpdateModel<Trade>(dbtrade, new string[] { "AreaId", "Location", "PostCode", "ReceiverName", "Tel", "Mobile", "PayId", "DistributionId", "HasInvoice", "InvoiceName", "BuyerMemo", "DeliveryPeriodType" });
                dbtrade.Order.Clear();
                foreach (var item in _CommonDao.GetCurrentCartItems(User.Identity.IsAuthenticated, _ShopContext, out totalFee))
                {
                    Order order = new Order();
                    order.ProductId = item.ProductId;
                    order.OrderPrice = item.Price;
                    order.OrderNum = item.Quanitiy;
                    order.OrderPoint = item.Point;
                    order.ProductName = item.ProductName;
                    dbtrade.Order.Add(order);
                }
                dbtrade.TotalFee = totalFee;
                mytrade.TotalPoint = mytrade.Order.Sum(x => x.OrderPoint);
                dbtrade.PostFee = _CommonDao2.GetById(dbtrade.DistributionId).Price;
                _TradeDao.SaveChanges();
                ViewData["totalfee"] = totalFee;
                return RedirectToAction("ConfirmTrade", "Trade", new { token = dbtrade.Token, tradeid = dbtrade.TradeId });
            }
        }


        //[Authorize]
        //private ActionResult UpdateShoppingCartSelect(string token, string tradeid)
        //{
        //    Trade trade = _TradeDao.FirstOrDefault(x => x.Token == token && x.TradeId == tradeid);
        //    return View();
        //}

        [Authorize]
        public ActionResult ConfirmTrade(string token, string tradeid)
        {
            AppendMeta("核对订单信息");
            decimal totalFee = 0;
            string currencyid = _ShopContext.Settings.CurrencyId.ToString();
            var pays = _PayDao.Find(x => x.CurrenyUnits.Contains(currencyid));
            ViewData.Add("Pays", pays);

            ViewData.Add("Distributions", _CommonDao2.GetAll());

            ViewData.Add("CartItems", _CommonDao.GetCurrentCartItems(User.Identity.IsAuthenticated, _ShopContext, out totalFee));

            ViewData["totalfee"] = totalFee;
            Trade trade = _TradeDao.FirstOrDefault(x => x.TradeId == tradeid && x.Token == token);
            if (trade == null)
                throw new ArgumentNullException();
            return View(trade);
        }



        [Authorize]
        [HttpPost]
        public ActionResult ConfirmTrade(FormCollection form, string token, string tradeid)
        {
            Trade trade = _TradeDao.FirstOrDefault(x => x.TradeId == tradeid && x.Token == token);
            if (trade != null)
            {
                if (trade.Pay.PayType == "2")//货到付款
                {
                    trade.TradeStatus = (int)TradeStatus.等待发货;
                    _CommonDao.DeleteCartItems(_ShopContext.CurrentUser.UserId);
                }
                else
                {
                    trade.TradeStatus = (int)TradeStatus.等待付款;
                    _CommonDao.DeleteCartItems(_ShopContext.CurrentUser.UserId);

                }
                _TradeDao.SaveChanges();
                return RedirectToAction("success", new { token = token, tradeid = tradeid, paytype = trade.Pay.PayType });
            }
            throw new ArgumentNullException();
        }

        [Authorize]
        public ActionResult Success(string tradeid, string token)
        {
            AppendMeta("订单提交成功");
            Trade trade = _TradeDao.FirstOrDefault(x => x.TradeId == tradeid && x.Token == token);
            var paytype= _PayPluginDao.GetPayModel(int.Parse(trade.Pay.PayType));
            ViewData["paytype"] = paytype;
            return View(trade);

        }


        [Authorize]
        public ActionResult TradeItem(string tid, string token)
        {
            AppendMeta("订单详情");
            Trade trade = _TradeDao.FirstOrDefault(x => x.TradeId == tid && x.Token == token);
            return View(trade);
        }


        
        public ActionResult ModifyCartItem(int pid, int quanitiy, string skuid)
        {
            try
            {
                CartItem cartitem = null;
                if (User.Identity.IsAuthenticated)
                {
                   cartitem=  _CommonDao.FirstOrDefault(x => x.ProductId == pid && x.UserId == _ShopContext.CurrentUser.UserId);
                }
                else
                {
                   cartitem=  _CommonDao.FirstOrDefault(x => x.ProductId == pid && x.SessionId == _ShopContext.SessionId);
                }
                cartitem.Quanitiy = quanitiy;
                _CommonDao.SaveChanges();
                return Content("1");
            }
            catch
            {
                return Content("0");
            }
        }


    }
}
